<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Admin_Controller extends MX_Controller{

	protected $controller = '';
	protected $is_main_controller = false;
	protected $is_special_action = false;
	protected $module = '';
	protected $module_id = 0;
	protected $module_name = 0;
	
	// Config table
	protected $table;
	protected $table_suffix;
	
	// Config List view
	protected $list_view_condition = '';
	protected $list_view_order_name = 'created';
	protected $list_view_order_direction = 'DESC';
	protected $list_view_status_show = true;
	protected $status_name = 'status';
	protected $list_view_created_show = true;
	protected $list_view_created_name = 'created'; // Not used
	protected $list_view_num_links = 3;
	protected $list_view_pagination = array(10,25,50,100);
	protected $list_view_searched_fields = array();
	protected $list_view_fields = array();
	protected $list_search_filter = array();
	protected $list_view_filter = array('created_from','created_to');
	protected $list_view_column_width_list = array(
													'column_header_number'=>30,
													'column_header_checkbox'=>30,
													'column_header_created'=>100,
													'column_header_status'=>70,
													'column_header_action'=>160
											);
	protected $obj_list; // Contain list view's result
	// Config Form view
	protected $form_view_fields = array();
	protected $form_view_allow_clean_old_file = true;
	
	// Config All columns/fields
	protected $fields = array();
	
	// Config css, javascript
	protected $css_list = array();
	protected $js_list = array();
	
	function __construct(){
		parent::__construct();
		$this->load->helper('main_helper');
		$this->load->helper('admin_helper');
		
		// Get controller
		$current_class = get_class($this);
		$controller = strtolower($current_class);
		// Get module (Normally module = controller -> No need to config module)
		$this->module = !empty($this->module) ? $this->module : $controller;
		$data['module'] = $this->module;
		
		// Config model
		$this->load->model($this->module.'_model','model');
		$this->model->module = $this->module;
		// Get table (Normally table_suffix = module -> No need to config table_suffix/table)
		$this->table_suffix = !empty($this->table_suffix) ? $this->table_suffix : $this->module;
		$this->table = !empty($this->table) ? $this->table : PREFIX.$this->table_suffix;
		$this->model->table = !empty($this->model->table) ? $this->model->table : $this->table;
		$this->model->status_name = !empty($this->model->status_name) ? $this->model->status_name : $this->status_name;
			
		if($this->uri->segment(1)=='admincp' && !$this->is_special_action){
			if(!$this->session->userdata('userInfo')){
				header('Location: '.PATH_URL.'admincp/login');
				return false;
			}
			
			// Check existing module
			$this->load->model('manager_modules/manager_modules_model');
			$get_module = $this->manager_modules_model->check_modules($this->module);
			if(!empty($get_module)){
				$this->module_id = $get_module[0]->id;
				$this->module_name = $get_module[0]->name;
			}
			
			// Get permission
			$this->load->model('admincp/admincp_model');
			$info = $this->admincp_model->getInfo($this->session->userdata('userInfo'));
			// if(!empty($info[0])){
				// $_SESSION['user_permission'] = $info[0]->permission;
			// }
			
			// Get config of List view and Form view
			$this->process_fields();
			$this->model->list_view_condition = $this->list_view_condition;
			$this->model->list_view_searched_fields = $this->list_view_searched_fields;
			$this->model->form_view_fields = $this->form_view_fields;
			$this->model->list_view_searched_filter = $this->list_search_filter;
			
			// Config css, javascript
			$data['css_list'] = $this->css_list;
			$data['js_list'] = $this->js_list;
			
			$this->load->vars($data);
			$this->template->set_template('admin');
			$this->template->write('title','Admin Control Panel');
		} else if(!empty($_SESSION['user'])){
			$user = $_SESSION['user'];
			$user_id = $user['id'];
			$user_data = $this->model->get('id,coin_number',ADMIN_USER_TABLE,"id = {$user_id}",true);
			if(!empty($user_data)){
				$user['coin_number'] = $user_data['coin_number'];
				$_SESSION['user'] = $user;
			}
		}
	}
	
	public function admincp_index(){
		admin_check_permission($this->module_id,'r',true);
		$get_name_module[0]=array();
		$get_name_module = $this->manager_modules_model->check_modules($this->module);
		$pagination_links = $this->admincp_get_pagination_links($this->input->post('start'),$this->list_view_pagination[0]);
		$data = array(
			'get_name_module'=>$get_name_module[0],
			'start' => $this->input->post('start'),
			'per_page' => $this->input->post('per_page'),
			'module_name'=>$this->module_name,
			'module' => $this->module,
			'list_view_order_name' => $this->list_view_order_name,
			'list_view_order_direction' => $this->list_view_order_direction,
			'search_field' => $this->list_view_searched_fields,
			'list_view_pagination' => $this->list_view_pagination,
			'search_filter'	=>	$this->list_search_filter,
			'list_view_filter'	=>	$this->list_view_filter,
			'list_view_column_width_list'	=>	$this->list_view_column_width_list,
			'pagination_links'=> $pagination_links

		);
	
		//Ajax search filter data
		if(!empty($this->list_search_filter)){
			$list_data = $this->model->fetch('*', $this->list_search_filter['data_table']);
			if(isset($this->list_search_filter['multi_level'])){
				$data['search_filter']['list_data'] = admin_get_multi_level_select($list_data, 0, $this->list_search_filter['multi_level']['parent_id_field_name'],$this->list_search_filter['multi_level']['parent_title_field_name']);
			}
			else{
				$data['search_filter']['list_data'] = admin_get_select_options($list_data, $data['search_filter']['parent_text']);
			}
			if(isset($data['search_filter']['sub_filter'])){
				$sub_list_data = $this->model->fetch('*', $this->list_search_filter['sub_filter']['data_table']);
				if(isset($this->list_search_filter['sub_filter']['multi_level'])){
					$data['search_filter']['sub_filter']['list_data'] = admin_get_multi_level_select($sub_list_data, 0, $this->list_search_filter['sub_filter']['multi_level']['parent_id_field_name'],$this->list_search_filter['sub_filter']['multi_level']['parent_title_field_name']);
				}
				else{
					$data['search_filter']['sub_filter']['list_data'] = admin_get_select_options($sub_list_data, $data['search_filter']['sub_filter']['parent_text']);
				}
			}
		}
		$this->session->set_userdata('start', $this->input->post('start'));
		$this->template->write_view('content','BACKEND/index',$data);
		$this->template->render();	
	}
	public function admincp_get_pagination_links($star = '', $per = '')
	{
		admin_check_permission($this->module_id,'w',true);
		$flag = FALSE;
		if($star == '' && $per == ''){
			$star = $this->input->post('start');
			$per = $this->input->post('per_page');
			$flag = TRUE;
		}
		$this->load->library('AdminPagination');
		$config['total_rows'] = $this->model->getTotalContent();
		$config['per_page'] = $per;
		$config['num_links'] = $this->list_view_num_links;
		$config['func_ajax'] = 'updatePagination';
		$config['start'] = $star;
		$this->adminpagination->initialize($config);
		if($flag){
			echo $this->adminpagination->create_links();
		} else {
			return $this->adminpagination->create_links();
		}
	}
	
	public function admincp_update($id=0){
		admin_check_permission($this->module_id,'w',true);
		$get_name_module[0]=array();
		$get_name_module = $this->manager_modules_model->check_modules($this->module);
		if($this->module == 'accounts'){
			if($id==1){
				if($this->session->userdata('userInfo')!='root'){
					header('Location:'.PATH_URL.'admincp/permission');
				}
			}
		}
		admin_check_permission($this->module_id,'r',true);
		$result = array();
		if($id!=0){
			$result = $this->model->getDetailManagement($id);
		}

		foreach($this->form_view_fields as $k => $form_view_config){
			$html = "<div class='row' id='row_{$k}'>".$this->form_field_build_field($form_view_config,$result, $id)."</div>";
			$form_view_config['html'] = $html;
			
			// Validate
			if(!empty($form_view_config['check_duplicate'])){
				$field_name = $form_view_config['name'];
				$remote_url = PATH_URL."admincp/{$this->module}/remote_check/{$field_name}/".$id;
				$validate_type = !empty($form_view_config['validate_type']) ? $form_view_config['validate_type'].', '  : '';
				$validate_type .=  "remote: '{$remote_url}'";
				$form_view_config['validate_type'] = $validate_type;
			}
			
			$this->form_view_fields[$k] = $form_view_config;
		}
		
		$data = array(
			'get_name_module'=>$get_name_module[0],
			'result'=>$result,
			'module'=>$this->module,
			'id'=>$id,
			'form_view_fields' => $this->form_view_fields
		);
		if($this->module == 'accounts'){
			$this->load->model('account_groups/account_groups_model');
			$list_group = $this->account_groups_model->list_groups();
			$data['list_group'] = $list_group;
		}
		// pr($this->form_view_fields,1);
		$this->template->write_view('content','BACKEND/ajax_editContent',$data);
		$this->template->render();
	}
	
	
	/******************** BEGIN: FORM PROCESSING ********************/
	public function admincp_save(){
		$result = array();
		admin_check_permission($this->module_id,'w',true);
		$obj = null;
		if($_POST){
			/*Begin: Save management*/
			$obj_id = (int)($this->input->post('hiddenIdAdmincp'));
			if($obj_id==0){
				$action = 'insert';
				$data = $this->admincp_form_get_data($action);
				$data = $this->before_save($data);
				$this->admincp_check_duplicate_field($data, $action, $obj_id);

				if($this->db->insert($this->table,$data)){
					$obj_id =  $this->db->insert_id();
					modules::run('admincp/saveLog',$this->module,$obj_id,'Add new','Add new');
				}
			} else {
				$obj = $this->model->get('*',$this->table,"id = {$obj_id}");
				if(!empty($obj)){
					$action = 'edit';
					$hinh=array('image','images_hover','images_thumb');
					foreach ($hinh as $view_img) {
						$del=$this->deleteImage($obj,$this->input->post('delete_'.$view_img));
					}

					$data = $this->admincp_form_get_data($action);
					$this->admincp_check_duplicate_field($data, $action, $obj_id);
					
					//Xử lý xóa hình khi update thay đổi hình
					if(!empty($result)){
						if(!empty($raw_data['FILES']['fileName'])){
							foreach($raw_data['FILES']['fileName'] as $k=>$v){
								@unlink('static/uploads/'.$this->module.'/' .$raw_data['FILES']['fileOption'][$k]. '/'.$result->$k);
								$data[$k] = $raw_data['FILES']['fileName'][$k];
							}
						}
						modules::run('admincp/saveLog',$this->module,$this->input->post('hiddenIdAdmincp'),'','Update',$result,$data);
					}
					$this->db->where('id',$this->input->post('hiddenIdAdmincp'));
					if(!$this->db->update($this->table,$data)){
						$obj_id = 0; // False result
					}
				}
			}
			/*End: Save management*/
			
			if ($obj_id) {
				$data = $this->admincp_form_upload_process($obj);
				if(!empty($data)){
					$this->model->update($this->table,$data,"id = {$obj_id}");
				}
				
				$this->after_save($obj_id);

				$result['message'] = 'success';
				$result['obj_id'] = $obj_id;
			}
		}
		echo json_encode($result);
	}
	
	public function admincp_form_get_data($action = 'insert'){
		$data = array();
		foreach($this->form_view_fields as $key => $form_view_config){
			// Set default values
			$form_view_config_func = !empty($form_view_config['func']) ? $form_view_config['func'] : '';
			$form_view_config_input_name = $form_view_config['input_name'];
			$form_view_config_input_value = $this->input->post($form_view_config_input_name);
			switch($form_view_config['type']){
				case 'text' :
				case 'textarea' :
				// case 'custom' :
					if(!empty($form_view_config_func)){
						$data[$key] = $this->admincp_form_func_process($form_view_config_input_value, $form_view_config_func, $form_view_config);
					} else {
						$data[$key] = $form_view_config_input_value;
					}
					break;
				
				case 'select':
					$select_config = $form_view_config['select_config'];
					if(!empty($select_config['sub_select_config'])){
						$sub_select_config = $select_config['sub_select_config'];
						if(empty($sub_select_config['func'])){
							$data[$sub_select_config['name']] = $this->input->post($sub_select_config['name']);
						} else {
							$data[$sub_select_config['name']] = $this->admincp_form_func_process($this->input->post($sub_select_config['name']), $sub_select_config['func']);
						}
					}
					if(!empty($form_view_config_func)){
						$data[$key] = $this->admincp_form_func_process($form_view_config_input_value, $form_view_config_func);
					} else {
						$data[$key] = $form_view_config_input_value;
					}
					break;
					
				case 'checkbox' :
					if($form_view_config_input_value=='on'){
						$status = 1;
					} else {
						$status = 0;
					}
					$data[$key] = $status;
					break;
				
				case 'password':
					if($action == 'insert') {
						$data[$key] = $this->admincp_form_func_process($form_view_config_input_value, $form_view_config_func);
					} else {
						if(!empty($form_view_config_input_value)){
							$data[$key] = $this->admincp_form_func_process($form_view_config_input_value, $form_view_config_func);
						}
					}
					break;
				case 'file':
					// if(is_array($fileName) && !empty($fileName[$form_view_config_input_name])){
						// $form_view_config_input_value = $fileName[$form_view_config_input_name];
						// $data[$key] = $form_view_config_input_value;
					// }
					break;
			}
		}
		
		if($action == 'insert'){
			$data['created'] = date('Y-m-d H:i:s');
		}
		return $data;
	}
	
	function admincp_form_func_process($form_view_config_input_value, $form_view_config_func, $form_view_config=''){
		switch($form_view_config_func){
			case 'slug' :
				return SEO($form_view_config_input_value);
			
			case 'upper':
				return mb_strtoupper($form_view_config_input_value , 'UTF-8');
			
			case 'password':
				return md5($form_view_config_input_value);
			
			case 'datetime':
				$value = $form_view_config_input_value;
				if(!empty($form_view_config['datetime_type'])){
					$datetime_type = $form_view_config['datetime_type'];
					switch($datetime_type){
						case 'date':
							$value = convertVNDate($form_view_config_input_value);
							break;
						case 'time':
							$value = convertVNTime($form_view_config_input_value);
							break;
						case 'datetime':
							$value = convertVNDatetime($form_view_config_input_value);
							break;
					}
				} else {
					$value = date('Y-m-d H:i:s', strtotime($form_view_config_input_value));
				}
				return $value;

			default :
				return $form_view_config_input_value;
		}
	}
	
	function deleteImage($obj,$linkimg=''){
		if(!empty($obj)){
					//$hinh=array('images','image','images_hover','images_thumb');
					//foreach ($hinh as $view_img) {
						foreach ($obj as $key => $link_images) {
							if($linkimg){
								//echo $link_images;
									@unlink('static/uploads/'.$this->module.'/image/' .$link_images);
									$link_images='';
									if($this->module=='categories'){
										$r=array(
											'images'=>$link_images,
											'images_hover'=>$link_images
												);
									}elseif($this->module=='gallery'){
										$r=array(
											'image'=>$link_images,												
												);
									}else{
										$r=array(
											'images'=>$link_images,												
											'images_thumb'=>$link_images												
												);											
									}
									
									$this->db->where('id',$this->input->post('hiddenIdAdmincp'));
									$this->db->update($this->table,$r);
									
							}
						}
					//}
				}
	}
	
	/*
	 * Server side: Only prevent saving duplicate object
	 */
	function admincp_check_duplicate_field($data, $action, $obj_id = 0){
		$result = true;
		foreach($this->form_view_fields as $key => $form_view_config){
			if(!empty($form_view_config['check_duplicate'])){
				$field_name = $key;
				if(!empty($data[$field_name])){
					$field_value = $data[$field_name];
					$condition = "{$field_name} = '{$field_value}'";
					if($action == 'edit' && !empty($obj_id)){
						$condition .= " AND id <> {$obj_id}";
					}
					$check_obj = $this->model->get('id',$this->table, $condition);
					if(!empty($check_obj)){
						$result = false;
						echo 'error-'.$key.'-exists';
						exit();
						break;
					}
				}
			}
		}
		return $result;
	}
	function admincp_remote_check($field_name, $obj_id=0){
		$result = false;
		$obj_id = (int)$obj_id;
		$field_name = trim($field_name);
		$input_name = 'input_'.$field_name;
		$field_value = $this->input->get($input_name);
		if(!empty($field_name) && !empty($field_value)){
			$condition = "{$field_name} = '{$field_value}'";
			if(!empty($obj_id)){
				$condition .= " AND id <> {$obj_id}";
			}
			$check_obj = $this->model->get('id',$this->table, $condition);
			$result = empty($check_obj);
		}
		echo json_encode($result);
	}
	
	private function admincp_form_upload_process($obj=null){
		$data = array();
		$this->load->library('upload');
		foreach($this->form_view_fields as $key => $form_view_config){
			// Reset to fix deleting all related files with the current obj
			$allow_clean_old_file = false;
			if($form_view_config['type'] == 'file' && !empty($form_view_config['file_config'])){
				$form_view_config_name = $form_view_config['name'];
				$form_view_config_input_name = $form_view_config['input_name'];
				
				// Submit to delete old file
				$input_delete_name = 'delete_'.$form_view_config_input_name;
				$input_delete_value = (int)$this->input->post($input_delete_name);
				$allow_delete_old_file = $input_delete_value;
				
				$file_config = $form_view_config['file_config'];
				$file_dir_path = $file_config['file_dir_path'];
				$encrypt_name = isset($file_config['encrypt_name'])? $file_config['encrypt_name'] : true;
				
				if(!empty($_FILES[$form_view_config_input_name])){
					$upload_config['allowed_types'] = '*';
					$upload_config['max_size'] = FILE_UPLOAD_MAX_SIZE;
					$upload_config['upload_path'] = BASEFOLDER.$file_dir_path;
					$upload_config['encrypt_name'] = $encrypt_name;// Encrypt file name
					$this->upload->initialize($upload_config);

					if($this->upload->do_upload($form_view_config_input_name)){
						$uploaded_data = $this->upload->data();
						$form_view_config_input_name_value = $uploaded_data['file_name'];
						$data[$key] = $form_view_config_input_name_value; // Fill upload info to data for saving
						
						// Clean old file
						if($this->form_view_allow_clean_old_file){
							$allow_clean_old_file = true;
						}
					} else {
						$upload_errors = $this->upload->display_errors();
						// pr($form_view_config_input_name);
						// pr($upload_errors);
					}
				}

				// Delete old file
				if(!empty($form_view_config_name) && !empty($obj->$form_view_config_name)){
					if(!empty($allow_delete_old_file) || !empty($allow_clean_old_file)){
						$old_value = $obj->$form_view_config_name;
						$old_file_path = BASEFOLDER.$file_dir_path.$old_value;
						try {
							if(file_exists($old_file_path)){
								unlink($old_file_path);
							}
						}catch (Exception $e) {}
					}
					if($allow_delete_old_file){
						$data[$key] = '';
					}
				}
			}
		}
		return $data;
	}
	
	protected function before_save($data){
		// For doing before saving
		return $data;
	}
	
	protected function after_save($obj_id){
		// For doing after saving
	}
	/******************** END: FORM PROCESSING ********************/
	
	
	public function admincp_delete(){
		admin_check_permission($this->module_id,'d',true);
		$id = (int)$this->input->post('id');
		if($id){
			// Before delete
			$this->before_delete($id);
			
			$obj = $this->model->getDetailManagement($id);
			modules::run('admincp/saveLog',$this->module,$id,'delete','delete');
			$this->db->where('id',$id);
			if($this->db->delete($this->table)){
				// Clean uploaded file after delete
				foreach($this->form_view_fields as $key => $form_view_config){
					if($form_view_config['type'] == 'file' && !empty($form_view_config['file_config'])){
						$form_view_config_name = $form_view_config['name'];
						
						$file_config = $form_view_config['file_config'];
						$file_dir_path = $file_config['file_dir_path'];
					
						// Delete old file
						if($this->form_view_allow_clean_old_file && !empty($obj->$form_view_config_name)){
							$old_value = $obj->$form_view_config_name;
							$old_file_path = BASEFOLDER.$file_dir_path.$old_value;
							try {
								if(file_exists($old_file_path)){
									@unlink($old_file_path);
								}
							}catch (Exception $e) {}
						}
					}
				}
				
				return true;
			}
		}
	}
	
	protected function before_delete($obj_id){
		// For doing after deleting
	}
	
	
	public function admincp_ajaxLoadContent() {
		$this->load->library('AdminPagination');
		$search_fields = $this->input->post('search_field');
		$limit = (int)$this->input->post('per_page');
		$start = $this->input->post('start');
		
		$config['total_rows'] = $this->model->getsearchContent($this->list_view_fields,$search_fields);
		$config['per_page'] = $limit;
		$config['num_links'] = $this->list_view_num_links;
		$config['func_ajax'] = 'searchContent';
		$config['start'] = $this->input->post('start');
		$this->adminpagination->initialize($config);
		if($this->module=='manager_modules'){
			$read_dir = scandir(BASEFOLDER.'application/modules');
			foreach($read_dir as $v){
				if($v!='.' && $v!='..' && $v!='home' && $v!='admincp'){
					if(!$this->model->check_modules($v)){
						$data_module = array(
							'name'=>ucfirst(str_replace('_',' ',$v)),
							'name_function'=>$v,
							$this->status_name=>0,
							'created'=>date('Y-m-d H:i:s')
						);
						$this->db->insert($this->table,$data_module);
					}
				}
			}
		}
		$this->obj_list = $this->model->getsearchContent($this->list_view_fields,$search_fields,$start,$limit);
		$data = array(
			'result' => $this->obj_list,
			'per_page' => $this->input->post('per_page'),
			'start' => $this->input->post('start'),
			'module' => $this->module,
			'search_field' => $this->input->post('list_view_searched_fields'),
			'list_view_status_show' => $this->list_view_status_show,
			'status_name' => $this->status_name,
			'list_view_created_show' => $this->list_view_created_show,
			'list_view_fields' => $this->list_view_fields,
			'controller'=>$this,
			'list_view_pagination' => $this->list_view_pagination
		);
		$this->session->set_userdata('start', $this->input->post('start'));
		$this->load->view('BACKEND/ajax_loadContent', $data);
	}
	
	protected function process_fields(){
		$this->_process_fields_for_view('list_view');
		$this->_process_fields_for_view('form_view');
		
		if(!empty($this->list_view_fields)){
			foreach($this->list_view_fields as $k => $field_config){
				$field_config['key'] = !empty($field_config['key']) ? $field_config['key'] : $k;
				// TODO: Removed!
				// Copy file_view
				if(empty($field_config['file']) && !empty($field_config['file_config'])){
					$file_config = $field_config['file_config'];
					$field_config['file_view'] = $file_config['file_type'];
					$field_config['images_dir_path'] = $file_config['file_dir_path'];
					if(empty($field_config['width'])){
						$field_config['width'] = !empty($file_config['file_width']) ? $file_config['file_width'] : 0;
					}
					if(empty($field_config['height'])){
						$field_config['height'] = !empty($file_config['file_height']) ? $file_config['file_height'] : 0;
					}
				}
				
				$this->list_view_fields[$k] = $field_config;
			}
		}
		if(!empty($this->form_view_fields)){
			foreach($this->form_view_fields as $k => $field_config){
				$field_config['key'] = !empty($field_config['key']) ? $field_config['key'] : $k;
				$field_config['name'] = !empty($field_config['name']) ? $field_config['name'] : $field_config['key'];
				$field_config['input_name'] = 'input_'.$field_config['name'];
				if(empty($field_config['func']) && !empty($field_config['datetime_type'])){
					$field_config['func'] = 'datetime';
				}
				
				// TODO: Removed!
				// Copy file_type
				if(empty($field_config['file']) && !empty($field_config['file_config'])){
					$file_config = $field_config['file_config'];
					$field_config['file_type'] = $file_config['file_type'];
					$field_config['images_dir_path'] = $file_config['file_dir_path'];
					if(empty($field_config['width'])){
						$field_config['width'] = !empty($file_config['file_width']) ? $file_config['file_width'] : 0;
					}
					if(empty($field_config['height'])){
						$field_config['height'] = !empty($file_config['file_height']) ? $file_config['file_height'] : 0;
					}
				}
				
				$this->form_view_fields[$k] = $field_config;
			}
		}
	}
	private function _process_fields_for_view($view){
		$is_empty_view_fields = false;
		switch($view){
			case 'list_view':
				$view_fields = &$this->list_view_fields; // Pointer
				break;
			case 'form_view':
				$view_fields = &$this->form_view_fields; // Pointer
				break;
		}
		if(empty($view_fields)){
			$is_empty_view_fields = true;
			$view_fields = array();
		}
		
		if($is_empty_view_fields && !empty($this->fields)){
			foreach($this->fields as $k => $field_config){
				if(isset($field_config[$view])){ // If having config 'list_view' or 'form_view' => Copy into $view_fields
					// Copy
					$view_field_config = $field_config[$view];
					// Clear
					unset($field_config['list_view']);
					unset($field_config['form_view']);
					
					if(!empty($view_field_config['text'])){
						unset($field_config['text']);
					}
					$view_field_config = array_merge($field_config,$view_field_config);
					
					$view_field_config['key'] = $k;
					$view_fields[$k] = $view_field_config;
				}
			}
		}
	}
	
	function form_field_build_field($form_view_config,$obj, $id = 0){
		// admin_check_permission($this->module_id,'w',true); // TODO
		$html = '';
		$data['form_view_config'] = $form_view_config;
		$data['result'] = $obj;
		$data['id'] = $id;
		
		switch($form_view_config['type']){
			case 'text':
			case 'password':
				$html = $this->load->view('BACKEND/form_view/text_and_password', $data, true);
				break;
			
			case 'textarea':
				$html = $this->load->view('BACKEND/form_view/textarea', $data, true);
				break;
			
			case 'checkbox':
				$html = $this->load->view('BACKEND/form_view/checkbox', $data, true);
				break;
			
			case 'select':
				$this->load->helper('admin_helper');
				if(!empty($form_view_config['select_config'])){
					$select_config = $form_view_config['select_config'];
					if(isset($select_config['value']) && is_array($select_config['value'])){
						$select_options = '';
						$key = $form_view_config['key'];
						foreach($select_config['value'] as $option_value => $option_text){
							$selected = (!empty($obj->$key) && $obj->$key == $option_value) ? 'selected="selected"' : '';
							$select_options .= "<option {$selected} value='{$option_value}'>{$option_text}</option>";
						}
						$data['select_options'] = $select_options;
					} else {
						$select_config['referred_condition'] = !empty($select_config['referred_condition']) ? $select_config['referred_condition'] : '';
						$option_list = $this->model->fetch('*', $select_config['referred_table_name'], $select_config['referred_condition']);
						if(!empty($select_config['multi_level_config'])){
							$multi_level_config = $select_config['multi_level_config'];
							$data['select_options'] = admin_get_multi_level_select($option_list, $parent_id = 0, $multi_level_config['parent_id_field_name'], $multi_level_config['parent_title_field_name']);
						} else {
							$data['select_options'] = $option_list;
						}
					}
					
					$data['CI'] = $this;
					$html = $this->load->view('BACKEND/form_view/select', $data, true);
				}
				break;
			
			case 'file':
				$data['file_width'] = !empty($field_config['file_width']) ? $field_config['file_width'] : (!empty($file_config['file_width']) ? $file_config['file_width'] : 0);
				$data['file_height'] = !empty($field_config['file_height']) ? $field_config['file_height'] : (!empty($file_config['file_height']) ? $file_config['file_height'] : 0);
				$html = $this->load->view('BACKEND/form_view/file', $data, true);
				break;
			
			case 'radio':
				// load_radio_view
				break;
			
			case 'gallery':
				$html = $this->load->view('BACKEND/form_view/gallery', $data, true);
				break;
				
			case 'custom': //load custom view
				$view_name = $form_view_config['view'];
				$html = $this->load->view('BACKEND/form_view/'.$view_name, $data, true);
				break;
		}
		
		return $html;
	}
	
	public function admincp_ajaxUpdateStatus(){
		if(!admin_check_permission($this->module_id,'w')){
			print '<script type="text/javascript">show_perm_denied()</script>';
			$status = $this->input->post('status');
			$data = array(
				$this->status_name => $status
			);
		} else {
			if($this->input->post('status')==0){
				$status = 1;
			}else{
				$status = 0;
			}
			$data = array(
				$this->status_name => $status
			);
			modules::run('admincp/saveLog',$this->module,$this->input->post('id'),'status','update',$this->input->post('status'),$status);
			$this->db->where('id', $this->input->post('id'));
			$this->db->update($this->table, $data);
		}
		
		$update = array(
			'status'=>$status,
			'id'=>$this->input->post('id'),
			'module'=>$this->module
		);
		$this->load->view('BACKEND/ajax_updateStatus',$update);
	
	}
	
	function admincp_uploadFiles(){
		$fileName = '';
		$fileOption = '';
		$tmp_name = '';
		if(count($_FILES) > 0 ){
			$fileOption = $this->model->getVarModel('listUploadField');
			foreach ($_FILES['fileAdmincp']['name'] as $key	=>	$value ){
				$fileName[$key]	=	'';
			}
			
			foreach($fileName as $k=>$v){
				if(isset($_FILES['fileAdmincp']['error'][$k])){
					$typeFile = explode('/',$_FILES['fileAdmincp']['type'][$k]);
					if($typeFile[0] == 'image' && $typeFile[0] == $fileOption[$k]){
						$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
						$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
						$ext = strtolower(substr($file_name[$k], -4, 4));
						if($ext=='jpeg'){
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-5)).'.jpg';
						}else{
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).$ext;
						}
					} else if($typeFile[0] == 'audio' && $typeFile[0] == $fileOption[$k]){
						$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
						$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
						$ext = strtolower(substr($file_name[$k], -3, 3));
						if($ext != 'mp3'){
							print 'Audio file extension not support';
							exit;
						} else {
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).'.mp3';
						}
					} else if($typeFile[0] == 'video' && $typeFile[0] == $fileOption[$k] ){
						$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
						$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
						$ext = strtolower(substr($file_name[$k], -3, 3));
						if($ext != 'flv' && $ext != 'mp4'){
							print 'Video file extension not support';
							exit;
						}else{
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).'.'.$ext;
						}
					}
					else{
						print 'File extension not support';
						exit;
					}

				}
			}
		}
		$data = array(
				'fileName'	=>	$fileName,
				'fileOption'	=>	$fileOption,
				'tmp_name'	=>	$tmp_name
			);
		return $data;
	}
	
	public function ajax_get_sub_select(){
		$sub_select_config = $this->input->post();
		$parent_id = (int)$this->input->post('value');
		$data = admin_build_sub_select_config($sub_select_config,$parent_id);
		echo $this->form_field_build_field($data,'');
	}
	
	public function ajaxGetFilter(){
		$data = $this->input->post();
		if($data['value'] == 'all')
			$condition = '';
		else	
			$condition = $data['condition'] . ' = ' . $data['value'];
		$list_data = $this->model->fetch('*', $data['data_table'], $condition);
		$options = '<option value="all">'.$data['default_parent_text'].'</option>';
		foreach($list_data as $k=>$v)
			$options .= '<option value="'.$v->id.'">'.$v->$data['parent_text'].'</option>';
		echo $options;
	}
		/*------------------------------------ Admin GALLERY ------------------------------------*/
	
	public function admincp_uploader($category_id=0, $key = ''){
		if($category_id!=0 && $key !='' ){
			$table = $this->form_view_fields[$key]['table'];
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: no-store, no-cache, must-revalidate");
			header("Cache-Control: post-check=0, pre-check=0", FALSE);
			header("Pragma: no-cache");

			// Settings
			$targetDir = BASEFOLDER.'static/uploads/'.$this->module.'/';
			@set_time_limit(5 * 60);

			// Get parameters
			$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
			$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
			$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

			// Clean the fileName for security reasons
			$fileName = preg_replace('/[^\w\._]+/', '', $fileName);

			// Make sure the fileName is unique but only if chunking is disabled
			if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
				$ext = strrpos($fileName, '.');
				$fileName_a = substr($fileName, 0, $ext);
				$fileName_b = substr($fileName, $ext);

				$count = 1;
				while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
					$count++;

				$fileName = $fileName_a . '_' . $count . $fileName_b;
			}
			
			//Code make folder
			check_dir_upload($targetDir);

			$ext = strtolower(substr($fileName, -4, 4));
			if($ext=='jpeg'){
				$fileName = date('Y').'/'.date('m').'/'.date('d').'/'.time().'_'.SEO(substr($_FILES['file']['name'],0,-5)).'.jpg';
			}else{
				$fileName = date('Y').'/'.date('m').'/'.date('d').'/'.time().'_'.SEO(substr($_FILES['file']['name'],0,-4)).$ext;
			}

			// Look for the content type header
			if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
				$contentType = $_SERVER["HTTP_CONTENT_TYPE"];

			if (isset($_SERVER["CONTENT_TYPE"]))
				$contentType = $_SERVER["CONTENT_TYPE"];


			// Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
			if (strpos($contentType, "multipart") !== FALSE) {
				if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
					// Open temp file
					$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
					if ($out) {
						// Read binary input stream and append it to temp file
						$in = fopen($_FILES['file']['tmp_name'], "rb");

						if ($in) {
							while ($buff = fread($in, 4096))
								fwrite($out, $buff);
						} else
							die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
						fclose($in);
						fclose($out);
						@unlink($_FILES['file']['tmp_name']);
						$data = array(
							'category_id'=>$category_id,
							'image'=>$fileName,
							$this->status_name=>1,
							'created'=>date('Y-m-d H:i:s',time())
						);
						if($this->db->insert(PREFIX.$table,$data)){
							modules::run('admincp/saveLog',$this->module,$this->db->insert_id(),'Add new','Add new','',$fileName);
						}
					} else
						die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
				} else
					die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			} else {
				// Open temp file
				$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
				if ($out) {
					// Read binary input stream and append it to temp file
					$in = fopen("php://input", "rb");

					if ($in) {
						while ($buff = fread($in, 4096))
							fwrite($out, $buff);
					} else
						die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

					fclose($in);
					fclose($out);
				} else
					die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
			}

			// Return JSON-RPC response
			//die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
		}
	}
	
	
	public function admincp_list_image_of_gallery($category_id, $key = ''){
		$table = $this->form_view_fields[$key]['table'];
		$data['list_image'] = $this->model->getListImageOfGallery($category_id, $table);
		$this->load->view('BACKEND/form_view/ajax_list_image_of_gallery',$data);
	}
	
	public function admincp_deleteImageGallery($key = ''){
		admin_check_permission($this->module_id,'d',true);
		if($this->input->post('id') && $key !=''){
			$table = $this->form_view_fields[$key]['table'];
			$id = $this->input->post('id');
			$result = $this->model->getDetailImageOfGallery($id, $table);
			modules::run('admincp/saveLog',$this->module,$id,'Delete','Delete');
			$this->db->where('id',$id);
			if($this->db->delete(PREFIX.$table)){
				//Xóa hình khi Delete
				@unlink('static/uploads/'.$this->module.'/'.$result->image);
				return true;
			}
		}
	}
	
	/*------------------------------------ End Admin GALLERY ------------------------------------*/
}